import React, {useContext, useEffect, useState} from 'react';
import {
    ActivityIndicator,
    Alert,
    Dimensions,
    ImageBackground,
    RefreshControl,
    ScrollView,
    StyleSheet,
    TextInput,
    TouchableOpacity,
    View
} from 'react-native';
import Clipboard from '@react-native-community/clipboard';
import {BottomSheet, Text} from 'react-native-elements';
import LocaleContext from '../libs/locale';
import WalletContext from '../libs/wallet';
import pool_bg from '../assets/Pool/pool_bg.png';
import pool_find from '../assets/Pool/pool_find.png';
import pool_print from '../assets/Pool/dyj.png';
import {
    getAllZhiYaHeYue,
    getBalances,
    getCurrentHeight,
    getMyZhiYaHeYue,
    getNodeStatus,
    getQryZhiYaHeYue,
    GetRedEnvelope, getTxInfo,
    getTxStatus,
    QueryRedEnvelope,
    tokenTransfer,
} from '../libs/nodes';
import WaitingModal from '../components/WaitingModal';
import LoadingView from '../components/LoadingView';
import {formartMoney} from "../libs/helpers";
import {constansts} from "../libs/constansts";
import {
    addRedEnvelopeGet,
    addTx,
    getRedEnvelopeGet,
    getTxFromSaveByhash,
    getTxs2,
    popTx,
    saveTX
} from "../libs/pendingTxs";
import Sound from "react-native-sound";
import Toast from "react-native-simple-toast";
import {useFocusEffect} from "@react-navigation/native";
import RedEnvelopeLoad from "./RedEnvelopeLoad";
import AsyncStorage from "@react-native-async-storage/async-storage";

const {width, height, scale} = Dimensions.get("window");

//TODO 矿池---》合约
//TODO java.lang.IllegalStateException: com.facebook.react.uimanager.IllegalViewOperationException: ViewManager for tag 517 could not be found.
const Pool = ({ navigation,route }: any) => {
    const locale = useContext(LocaleContext);
    const wallet: any = useContext(WalletContext);
    const [balances, setBalances] = useState({ SAT: '', tokens: [] });
    const [refresh, setRefresh] = useState(true);//“刷新”标识
    const [seachTxt,setSeachTxt] = useState('');          //合约搜索文字
    const [seachTxtError,setSeachTxtError] = useState('');//合约搜索文字Err
    const [msgInfo,setMsgInfo] = useState('');            //提示信息
    const [transferCreateVisible,setTransferCreateVisible] = useState(false);//显示或隐藏“创建质押合约”对话框
    const [createHyError,setCreateHyError] = useState('');//创建合约中金额错误提示
    const [hyMoney,setHyMoney] = useState('');            //创建合约中金额
    const [bshow,setBshow] = useState(false);//TODO 2021-03-06 loading显示或隐藏状态
    const [prompt,setPrompt] = useState('')  ;//TODO 2021-03-06 loading对话框文字
    const [bShowLoading,setBShowLoading] = useState(false);//TODO 2021-03-06 gif—loading显示或隐藏状态
    const [hyMyList, setHyMyList] = useState<any>([]);     //我的合约列表
    const [bhyMyListShow,setBhhyMyListShow] = useState(false);//我的合约列表显示或隐藏03-10
    const [hyAllList, setHyAllList] = useState<any>([]);   //所有合约列表
    const [bhyAllListShow,setBhyAllListShow] = useState(false);//所有合约列表显示或隐藏03-10
    const [bShowTip,setBShowTip] = useState(false); //是否提示
    const [addressIn,setAddressIn] = useState('');//返回的地址串;
    const [operateType,setOperateType] = useState('');//操作类型, 添加 取回 二次取回 转移...
    const [requestMoney,setRequestMoney] = useState('');//执行成功的money;

    const [totalProof,setTotalProof] = useState(0.0); //总凭证;
    const [myProof,setProof] = useState(0.0); //我的凭证;

    const [onLineListData,setOnLineListData] = useState<any>([]);//在线item集;

    const [status,setStatus]:any = useState(new Array(constansts.poolMyList.length).fill("20"));

    // const [onLineList,setOnLineList] = useState<any>([]);

    //接收广播操作完成 返回 是否需要等待 操作完成;
    // InteractionManager.runAfterInteractions(() => {
    //     // ...需要长时间同步执行的任务...
    //   });

    const colorZy = "#ACACAC";
    const fontSizeZy = 13;
    const fontSizeValue = 16;
    const buttomInterval = 1;

    var AllContract:any = [];
    var MyContract:any = null;

    const getPoolTranInfo = async () => {
        let res =  await AsyncStorage.getItem("poolShowInfo");
        if(res)
        {
            constansts.poolShowInfo = JSON.parse(res);
        }
        else
        {
            return null;
        }
    }
    //初始化 bShowTip
    useEffect(()=>{
        const initbShowTip = async () => {
            console.log(`开始初始化tranHY`)
            let allTrans = await getTxs2();
            console.log(`alltrans:`)
            console.log(allTrans)
            if(allTrans === [])
            {
                constansts.tranHY = [];
                await AsyncStorage.setItem("tranHY","[]")
                setBShowTip(false);
                constansts.poolShowTip = false;
                return;
            }
            else
            {
                let traningNum = 0;
                for(let i = 0 ; i < allTrans.length ; i++)
                {
                    if(allTrans[i].height == -1 )
                    {
                        traningNum++;
                    }
                }
                if(traningNum > 0)
                {
                    let tranHY = await AsyncStorage.getItem("tranHY");
                    console.log(`tranHY`)
                    console.log(tranHY)
                    if(tranHY)
                    {
                        constansts.tranHY = JSON.parse(tranHY);
                        if(constansts.tranHY.length > 0)
                        {
                            constansts.poolShowTip = true;
                            await getPoolTranInfo();
                            setBShowTip(true);
                            return;
                        }
                        constansts.poolShowTip = false;
                        setBShowTip(false);
                    }
                }
            }
        }
        initbShowTip();
    },[])

    const compareAll = (prop:any)=>  {
        return function (obj1:any, obj2:any) {
            var val1 = obj1[prop].toLowerCase();
            var val2 = obj2[prop].toLowerCase();
            if (val1 < val2) {
                return -1;
            } else if (val1 > val2) {
                return 1;
            } else {
                return 0;
            }
        }
    }
    const compareAllSAT = (prop:any)=>  {
        return function (obj1:any, obj2:any) {
            var val1 = parseFloat(obj1[prop]);
            var val2 = parseFloat(obj2[prop]);
            if (val1 < val2) {
                return -1;
            } else if (val1 > val2) {
                return 1;
            } else {
                return 0;
            }
        }
    }

    const compareMy = (prop:any)=>  {
        return function (obj1:any, obj2:any) {

            obj1 = JSON.parse(obj1);
            obj2 = JSON.parse(obj2);
            // console.log("obj1="+obj1[prop]);
            var val1 = obj1[prop].toLowerCase();
            var val2 = obj2[prop].toLowerCase();
            if (val1 < val2) {
                return -1;
            } else if (val1 > val2) {
                return 1;
            } else {
                return 0;
            }
        }

    }

    //利用全局变量初始化数据
    useEffect(()=>{
        if(constansts.poolAllList.length>0) {
            console.log("这里是计算")
            // console.log("计算一下"+0?"true":"false")
            setHyAllList(constansts.poolAllList);
            setBhyAllListShow(true)
        }
        if(constansts.poolMyList.length>0)
        {
            var statusList = status;

            for(var i = 0;i<constansts.poolMyList.length;i++)
            {
                statusList[i]="20";
            }
            setStatus(statusList);
            setHyMyList(constansts.poolMyList);
            setBhhyMyListShow(true);
            setOnLineListData(constansts.onLineListTempt);
        }
    },[])

    //查询正在进行中的合约交易
    const workInterval = async ()=>{
        console.log("查询正在进行中的合约交易")
        console.log(constansts.tranHY)
        try {
            constansts.tranHY.map(async (item:any,index:any)=>{
                let res = await getTxFromSaveByhash(constansts.tranHY[index].hash)
                if(res == null || res.height !== -1)
                {
                    await updateTranHY(index);
                }
            })
        }catch (e) {
            console.log("Poolpopfalse==>"+e)
        }
    }
    const updateTranHY = async (index: number) => {
        constansts.poolShowTip = false;
        setBShowTip(false);
        constansts.tranHY.splice(index, 1);
        await AsyncStorage.setItem("tranHY", JSON.stringify(constansts.tranHY))
        constansts.poolShowInfo = {addressIn:"",operateType:"",requestMoney:""};
        await AsyncStorage.setItem("poolShowInfo",JSON.stringify(constansts.poolShowInfo))
    }

    useEffect(() => {
        const t=setInterval(workInterval,10000);
        return ()=>{
            clearInterval(t);
        }

    },[bShowTip]);//定时器查询合约交易 10S

    useEffect(() => {

        if (constansts.isPool == 0) {
            constansts.isPool = 1;
            navigation.addListener('focus', () => {
                console.log("fouus Pool");
                // console.log("矿池全局数据before："+JSON.stringify(constansts.poolAllList))

                // work();
            });
        }
    },[]) //添加focus

    //获取余额
    const work = async () => {
        if (!refresh) {
            return;
        }
        setRefresh(false);
        console.log("refresh Pool");
        try {
            const balances = await getBalances(wallet.address);
            console.log("getBalances===>"+JSON.stringify(balances));
            constansts.SATcount = balances.SAT;
            await AsyncStorage.setItem("Asset_SATcount",(balances.SAT).toString())
            constansts.Balance = balances;
            console.log("Pool的Balances==>"+JSON.stringify(constansts.Balance))
            setBalances(balances);
        } catch (e) {
            console.log('getBalances:', e);
        }
    };
    //所有合约列表
    const workAllList = async () => {
        try {
            // const NodeStatus = await getNodeStatus();
            // console.warn("Network Excute Network ExcuteNetwork Excute");
            const info = await getAllZhiYaHeYue();
            const currentHeight = await getCurrentHeight();
            // console.log("getAllZhiYaHeYue-->"+JSON.stringify(info));
            let arr = [];
            for(var i in info){
                // console.log(`${i} -->${JSON.stringify(info[i])}`);
                //gcLcf7oAWbAJFMFSo15w9vuvDdpkNjrAU -->{"Address":"gcLcf7oAWbAJFMFSo15w9vuvDdpkNjrAU","Contract":null,"Amount":"40422434.6569","Start":1,"End":-1,"LBH":275074}
                //h4r5qRSATdf8vikw4H1eKBin2rk9FTpf3 -->{"Address":"h4r5qRSATdf8vikw4H1eKBin2rk9FTpf3","Contract":"dQBfZNSRpeo3Wii8hwHASZfmi2WUgYwym","Amount":"7282052.43844707","Start":62001,"End":-1,"LBH":277246}
                if (info[i].Contract && parseInt(info[i].LBH)>(parseInt(currentHeight)-120)) {
                    info[i].status ="20";
                    arr.push(info[i])
                }
            }
            // console.log("ZYHY-->"+arr.length)
            arr.sort(compareAll("Contract"));
            AllContract = arr;
            constansts.poolAllList = AllContract;
            // console.log("总的质押合约数据==》"+JSON.stringify(AllContract))
            if (arr.length>0){
                // console.log("总的质押合约有--》"+arr.length+"个")
                setHyAllList(arr);
                setBhyAllListShow(true)
                // setBhyAllListShow(false)
            }
            else{
                setHyAllList(arr);
                // setBhyAllListShow(false)
            }
            //setHyAllList
        } catch (e) {
            console.log('getAllZhiYaHeYue:', e);
        }
    };
    //所有合约列表，按照逆序年华排序
    const workAllList2 = async () => {
        try {
            console.log(JSON.stringify(constansts.poolAllList))
            console.log("1")
            setBhyAllListShow(false)
            console.log(JSON.stringify(hyAllList))
            var arr = constansts.poolAllList;
            arr.sort(compareAllSAT("Amount"));

            AllContract = arr;
            setHyAllList(arr);
            setBhyAllListShow(true)
            constansts.poolAllList = arr;

            console.log(JSON.stringify(arr))
            console.log("2")

            // const NodeStatus = await getNodeStatus();
            //
            // // console.warn("Network Excute Network ExcuteNetwork Excute");
            // const info = await getAllZhiYaHeYue();
            // const currentHeight = await getCurrentHeight();
            // // console.log("getAllZhiYaHeYue-->"+JSON.stringify(info));
            // let arr = [];
            // for(var i in info){
            //     // console.log(`${i} -->${JSON.stringify(info[i])}`);
            //     //gcLcf7oAWbAJFMFSo15w9vuvDdpkNjrAU -->{"Address":"gcLcf7oAWbAJFMFSo15w9vuvDdpkNjrAU","Contract":null,"Amount":"40422434.6569","Start":1,"End":-1,"LBH":275074}
            //     //h4r5qRSATdf8vikw4H1eKBin2rk9FTpf3 -->{"Address":"h4r5qRSATdf8vikw4H1eKBin2rk9FTpf3","Contract":"dQBfZNSRpeo3Wii8hwHASZfmi2WUgYwym","Amount":"7282052.43844707","Start":62001,"End":-1,"LBH":277246}
            //     if (info[i].Contract && parseInt(info[i].LBH)>(parseInt(currentHeight)-120)) {
            //         // for(var ii=0;ii<NodeStatus.length;ii++ )
            //         // {
            //         //     if(NodeStatus[ii].Key==i)
            //         //     {
            //         //         info[i].status = NodeStatus[ii].Value;
            //         //         break;
            //         //     }
            //         // }
            //         info[i].status ="20";
            //         arr.push(info[i])
            //     }
            // }
            // // console.log("ZYHY-->"+arr.length)
            // // arr.sort(compareAll("Contract"));
            // AllContract = arr;
            // constansts.poolAllList = AllContract;
            // // console.log("总的质押合约数据==》"+JSON.stringify(AllContract))
            // if (arr.length>0){
            //     // console.log("总的质押合约有--》"+arr.length+"个")
            //     setHyAllList(arr);
            //     setBhyAllListShow(true)
            //     // setBhyAllListShow(false)
            // }
            // else{
            //     setHyAllList(arr);
            //     // setBhyAllListShow(false)
            // }
            // //setHyAllList
        } catch (e) {
            console.log('SortAllZhiYaHeYue:', e);
        }
    };
    //我的合约列表
    const workMineList = async () => {
        try {
            //获取在线全部质押合约数据
            let arr=AllContract;


            //获取自己的质押合约数据
            const info = await getMyZhiYaHeYue(wallet.address);

            // const info = JSON.parse(sourceInfo);
            // console.log("getMyZhiYaHeYue-->"+JSON.stringify(info));
            let hyMyArr = [];
            let onLineListTempt = [];
            for(var i in info){
                var ii = parseInt(i)-1;

                // console.log(`${i} -->${JSON.stringify(info[i])}`);
                if(JSON.parse(info[i])[7]){
                    for(var allP in arr){
                        // console.log("arr[allP]==>"+arr[allP])
                        if(JSON.parse(info[i])[0] == arr[allP].Contract)
                        {
                            // console.warn('workMineList OffLine ===>>> '+ info[i]);
                            onLineListTempt.push(JSON.parse(info[i]));
                        }
                    }
                    JSON.parse(info[i])[8]="20";
                    hyMyArr.push(info[i])
                }
            }
            hyMyArr.sort(compareMy(0));
            MyContract = hyMyArr;
            constansts.poolMyList = MyContract;
            (constansts.onLineListTempt as any) = onLineListTempt;
            // console.log("我的显示合约的数据==》"+hyMyArr)
            // console.log("我的显示质押合约的长度==》"+hyMyArr.length)
            // console.log("我的显示质押合约在线的长度==》"+onLineListTempt.length)
            if (hyMyArr.length > 0){
                setHyMyList(hyMyArr);
                setBhhyMyListShow(true);
                setOnLineListData(onLineListTempt);
                // console.warn('workMineList OneLine ===>>> '+ onLineListData.length);
            }else{
                console.log("getMyZhiYaHeYue--> NULL--------->");
                setHyMyList(hyMyArr);
                setBhhyMyListShow(false);
            }
        } catch (e) {
            console.log('getMyZhiYaHeYue:', e);
        }
    };
    //合约状态
    const workStatus = async () => {
        //设置全部列表的合约状态
        // constansts.poolAllList;
        // console.log("设置全部列表的合约状态-->"+JSON.stringify(constansts.poolAllList))

        const NodeStatus = await getNodeStatus();
        for(var i=0;i<constansts.poolAllList.length;i++)
        {
            for(var ii=0;ii<NodeStatus.length;ii++ )
            {
                if(NodeStatus[ii].Key==constansts.poolAllList[i].Address)
                {
                    constansts.poolAllList[i].status = NodeStatus[ii].Value;
                    break;
                }
                if(ii===NodeStatus.length-1)
                {
                    constansts.poolAllList[i].status ="20";
                }
            }
        }
        AllContract = constansts.poolAllList;
        setBhyAllListShow(false)
        setHyAllList(AllContract);
        setBhyAllListShow(true)
    };

    const initWork = async ()=>{
        await work();
        await workAllList();
        await workMineList();
        await workStatus();
        // console.log("????????????")
    }

    useEffect(() => {//我的余额
        workInterval();
        initWork();
    }, [refresh]);

    //合约搜索
    const inputOnEndEditing = async ()=>{
        try {
            if(seachTxt=="")
            {
                return ;
            }
            const info = await getQryZhiYaHeYue(wallet.address,seachTxt);
            //setHyAllList
            console.log("getQryZhiYaHeYue-->"+JSON.stringify(info));
            // let hy = {"Address":info[1],"Contract":info[0],"Amount":info[4]}
            setBhyAllListShow(false)
            let marchResult = false;
            for(var i in hyAllList){
                if(hyAllList[i].Contract == info[0]){
                    marchResult = true;
                    break;
                }
            }
            let hy = {"Address":info[1],"Contract":info[0],"Amount":info[4],"IsOnLine":marchResult}
            let arr = [];
            arr.push(hy)
            setHyAllList(arr);
            setBhyAllListShow(true)
            setSeachTxt('');
            setBhhyMyListShow(false)
        } catch (e) {
            console.log('inputOnEndEditing:', e);
            setSeachTxt('');
            Alert.alert("",locale?._("pool.op.contractNonExit"),[{text: (locale?._('Assets.send.OK') as any)}]);
        }
    };

    //TODO 接收上个页面传回来的值;
    const getPreviousParams = (isNeedWait:boolean, addressIn:string, operateType:string, requestMoney:any)=>{
        constansts.poolShowTip = isNeedWait;
        setBShowTip(isNeedWait);//是否需要等待;
        constansts.poolShowInfo.addressIn = addressIn;
        constansts.poolShowInfo.operateType = operateType;
        constansts.poolShowInfo.requestMoney = requestMoney;
        AsyncStorage.setItem("poolShowInfo",JSON.stringify(constansts.poolShowInfo))
        setAddressIn(addressIn);
        setOperateType(operateType);
        if(requestMoney){
            setRequestMoney(requestMoney);
        }else{
            setRequestMoney('');
        }
    }

    //TODO 创建合约
    const onCreateHy = async (hyMoney:any)=>{
        setTransferCreateVisible(false);
        try {
            var temp=0;
            try {
                hyMoney = formartMoney(hyMoney,8);
                if (hyMoney == "" || parseFloat(hyMoney) <= 0) {
                    temp=1;
                }
            }catch (e) {
                temp=1;
            }

            if(temp==1)
            {
                Alert.alert("",(locale?._("pool.op.minCreateContract") as any),[{text: (locale?._('Assets.send.OK') as any)}]);
                return;
            }
            if(parseFloat(hyMoney)+0.002>parseFloat(constansts.Balance.SAT))
            {
                Alert.alert("",(locale?._("serviceChargeError") as any),[{text: (locale?._('Assets.send.OK') as any)}]);
                return ;
            }

            setBshow(true);//TODO 2021-03-06
            // //{keypairSeed:wallet.seed，Sender:钱包地址，tokenAddress:PledgeFactory ，Data:pairCreated("h43Bqnj7g32bHn44VDnK6XbFoFPL34hXf","金额")，}
            const tx:any = await tokenTransfer(wallet.seed, wallet.address, constansts.PledgeFactory, `pairCreated("${constansts.ERCsat}","${hyMoney})"`,'',"");

            //添加进入列表
            if (tx.reason!=1)
            {
                console.log("false reason="+tx.reason+"     "+ tx.data);
                setBshow(false);//TODO 2021-03-06
                Alert.alert(tx.reason.toString(), locale?._('Assets.send.sendFail'),locale?._('Assets.send.OK') as any);
                return;
            }
            else
            {
                await addTx(tx);
                (constansts.tranHY as any).push(tx);
            }

            console.log("onCreateHy=======>>>>> "+JSON.stringify(tx));
            constansts.poolShowInfo.addressIn=tx.hash;
            (constansts.poolShowInfo.operateType)=locale?._('Pool.zyhy.create');
            constansts.poolShowInfo.requestMoney=hyMoney;
            await AsyncStorage.setItem("poolShowInfo",JSON.stringify(constansts.poolShowInfo))
            setAddressIn(tx.hash);
            setOperateType('创建质押');
            setRequestMoney(hyMoney);
            //onCreateHy-->{"hash":"51a681dd6b60af51e52ebce6b5032893b65adcef9ad780285b77c0a08049376e","timestamp":1615389729495,"amount":"","addressIn":"SvoZS1E4n7L44cWkpP8eQaZwWXXx4A4u9","addressOut":["pairCreated(h43Bqnj7g32bHn44VDnK6XbFoFPL34hXf\"","\"0.0001\""],"data":"pairCreated(\"h43Bqnj7g32bHn44VDnK6XbFoFPL34hXf\",\"0.0001)\"","height":0}
            setBshow(false);//TODO 2021-03-06
            Alert.alert('', locale?._('Assets.send.sendSuccess'),[{text:locale?._('Assets.send.OK'),onPress:()=>{
                constansts.poolShowTip =true;
                setBShowTip(true);
            }}]);
            // navigation.replace('Txs', { kind: 'Pending' });
        } catch (e) {
            console.log('onCreateHy:', e);
            Alert.alert('', 'onCreateHy---Err');
        }
    };

    //显示提示框执行的内容
    const showNeedExcuteContent=()=>{
        return locale?._('pool.op.pooling')+":"+ constansts.poolShowInfo.operateType + ' ' + constansts.poolShowInfo.requestMoney;
    }

    //格式化JSON
    const parseFilterJsonData = (item:any,postion:number)=>{
        return JSON.stringify(item).split(',')[JSON.stringify(item).split(',').length-postion].replace('[','').replace('\\"','').replace('\\"','').replace('\"','');
    }

    // 我的占比
    const calculateMyPercent = (item:any)=>{
        return parseFloat(JSON.stringify(item).split(',')[JSON.stringify(item).split(',').length-3].replace('[','').replace('\\"','').replace('\\"','').replace('\"',''))
        /parseFloat(parseFilterJsonData(item,2))
    }

    // 我的收益
    const calculateMyIncome = (item:any)=>{
        return calculateMyPercent(item)
        *parseFloat(parseFilterJsonData(item,5))
    }

    // 计算年化率
    const calculateYearRate = (item:any)=>{
       return Math.ceil
        ((4204800 /parseFloat(parseFilterJsonData(item,5)))*100).toFixed(0);
    }

    //对比是否为在线Online
    const contractAddressEqual = (item:any,index:number)=>{
        let resultEqual = true;
        // console.log("contractAddressEqual =====> "+ JSON.stringify(constansts.poolAllList));
        // console.log("contractAddressEqual2 =====> "+ item);
        // console.log("contractAddressEqual =====>"+JSON.stringify(hyMyList) )
        var statusList = status;
        statusList[index]="20";
        for(var i=0;i<constansts.poolAllList.length;i++){
            // console.log("检查在线问题"+i+constansts.poolAllList[i].Contract)
            // console.log("检查在线问题"+i+JSON.parse(item)[0])
            if(constansts.poolAllList[i].Contract == JSON.parse(item)[0]){
                statusList[index] = constansts.poolAllList[i]==null?"20":constansts.poolAllList[i].status;
                resultEqual = true;
                break;
            }
            statusList[index]="0";
            resultEqual=false;
        }
        setStatus[statusList];
        return resultEqual;
    }

    const searchResultIsOnLine = (item:any)=>{
        if(null == item.IsOnLine || item.IsOnLine){
            return true;
        }
        return false;
    }

    //粘贴;
    const fetchCopiedText = async () => {
        try{
            const str = await Clipboard.getString();
            setSeachTxt(str);
        }catch(e){
            console.log("fetchCopiedText====>>>> "+e);
        }
    };

    //测试红包领取页面
    const [showRedEnvelopeLoad,setShowRedEnvelopeLoad] = useState(false);
    const [pkgid,setPkgid] = useState("");
    const [coverTxt,setCoverTxt] = useState("");
    const [sender,setSender] = useState(true)//红包的发送人
    const [loadType,setLoadType] = useState('0');

    //添加进代币的内容
    const [openRedEnvelopeConAddress,setOpenRedEnvelopeConAddress] = useState('');
    const [openRedEnvelopeTokenName,setOpenRedEnvelopeTokenName] = useState('');
    const [openRedEnvelopeUrl,setOpenRedEnvelopeUrl] = useState('');

    const playSound = (name:string) =>{
        Sound.setCategory('Playback') // 在静音模式下启用播放'
        let whoosh = new Sound(name, Sound.MAIN_BUNDLE, (error) => {
            whoosh.play((success) => {
                whoosh.release()
            })
        })
    }
    const getClipboardString = async () => {
        const content = await Clipboard.getString();
        return content;
    }
    const RedEnvelopeLoadBack =  (res: any) => {
        setShowRedEnvelopeLoad(false);
        console.log(res)
        if (res == "0") {
        } else if (res == "1") {
            playSound("openred.mp3");
            GetRedEnvelope(wallet.address, pkgid).then(
                async ()=>{

                    console.log(`openRedEnvelopeConAddress=${openRedEnvelopeConAddress}`)
                    if(openRedEnvelopeConAddress !== "")
                    {
                        for(var i=0;i<(constansts.addTokens).length;i++)
                        {
                            //如果有相同的就只接跳出
                            if( (constansts.addTokens[i] as any).address===openRedEnvelopeConAddress)
                            {
                                break;
                            }
                            //到最后一个并且不相同 添加再退出
                            if((constansts.addTokens[i] as any).address!==openRedEnvelopeConAddress && i === ((constansts.addTokens).length - 1))
                            {
                                (constansts.addTokens as any).push({address:openRedEnvelopeConAddress,url:openRedEnvelopeUrl,desc:openRedEnvelopeTokenName});
                                console.log(`添加后的代币列表:${JSON.stringify(constansts.addTokens)}`)
                                await AsyncStorage.setItem('@addTokens',JSON.stringify(constansts.addTokens as any));
                                break;
                            }
                        }
                        if((constansts.addTokens).length === 0 )
                        {
                            (constansts.addTokens as any).push({address:openRedEnvelopeConAddress,url:openRedEnvelopeUrl,desc:openRedEnvelopeTokenName});
                            console.log(`添加后的代币列表:${JSON.stringify(constansts.addTokens)}`)
                            await AsyncStorage.setItem('@addTokens',JSON.stringify(constansts.addTokens as any));
                        }

                    }

                    navigation.navigate('RedEnvelopeInfo', { pkgid: pkgid});
                    await addRedEnvelopeGet(pkgid);
                }

            );

        } else if (res == "2") {
            navigation.navigate('RedEnvelopeInfo', { pkgid: pkgid});
        }
    }
    const work2 = async () => {
        // await AsyncStorage.setItem('@addRedEnvelopeGet', "[]")
        const ClipboardString = await getClipboardString();
        // console.log("剪贴板的内容==》" + ClipboardString);
        if (ClipboardString == "") {
            return;
        }
        var RedEnvelopeReceivedList = await getRedEnvelopeGet();
        // console.log("数组信息"+JSON.stringify(RedEnvelopeReceivedList))
        if (ClipboardString == "") {
            return;
        }
        var password ="";
        if(ClipboardString.indexOf("(")!==-1&&ClipboardString.indexOf(")")!==-1)
        {
            password = ClipboardString.slice(ClipboardString.indexOf("(")+1,ClipboardString.indexOf(")"));
        }
        else
        {
            password=ClipboardString;
        }
        if (RedEnvelopeReceivedList.indexOf(password) !== -1 || password.length!==15) {
            return;
        }

        try {
            var result: any = await QueryRedEnvelope(password);
            var sender = result.dict.nickname || result.dict.sender;
            setOpenRedEnvelopeConAddress (result.dict.type || "");
            setOpenRedEnvelopeTokenName(result.dict.coinname || "");
            setOpenRedEnvelopeUrl ( result.dict.url || "");
            setCoverTxt(result.dict.desc);
            if (sender !== "") {
                await addRedEnvelopeGet(password);
                setPkgid(password);
                setSender(sender);
                var temp = 0;//0是红包还有可以强，并且没抢过这个红包。   1是抢过这个红包了。   2是红包没了，手速慢了
                if (result.pkgitems.length < parseInt(result.dict.number))//红包还有，里面区分0和1
                {
                    if (result.pkgitems.length != 0) {
                        for (var i = 0; i < result.pkgitems.length; i++) {
                            if (result.pkgitems[i].getter == wallet.address) {
                                temp = 1;
                                break;
                            }
                        }
                    } else {
                        temp = 0;
                    }

                } else if (result.pkgitems.length >= parseInt(result.dict.number)) //红包没了 ，里面区分抢过了1和没抢过2
                {
                    if (result.pkgitems.length != 0) {
                        for (var i = 0; i < result.pkgitems.length; i++) {
                            if (result.pkgitems[i].getter == wallet.address) {
                                temp = 1;
                                break;
                            }
                            if (i == result.pkgitems.length - 1) {
                                temp = 2;
                            }
                        }
                    } else {
                        temp = 2;
                    }
                } else {
                    temp = 0;
                }
                if (temp == 1) {
                    Toast.show("该红包您已经抢过了")
                    navigation.navigate('RedEnvelopeInfo', {pkgid: password});
                } else {
                    console.log("进入这里了呀")
                    setLoadType(temp.toString())
                    setShowRedEnvelopeLoad(true);
                }

            } else {
                // Alert.alert("", "没有此口令。");
            }
        } catch (e) {
            console.log("抢红包错误==》" + e)
            return;
        }

    }
    useFocusEffect(
        React.useCallback(() => {
            const t = setInterval(work2,1000);//监控剪贴板
            return ()=> {
                clearInterval(t)
            };
        }, [])
    );

    const log = (i:any) =>{
        // console.log(`日志是:${(i>0).toString()}`)

        return i;
    }


    return (
        <View>
            <ScrollView refreshControl={
                <RefreshControl refreshing={false} onRefresh={() => setRefresh(true)} collapsable={true} />
            }>
                <View style={{ backgroundColor: '#FAFBFDFF' }}>
                    {/***智图钱包  进度条图标+文字（操作提示）****/}
                    <ImageBackground source={pool_bg}
                    resizeMode={'stretch'}
                    style={
                        {
                            width: 425,
                            height:140,
                        }} >
                        <View style={{marginLeft:16,marginTop:30,flexDirection:'column',height:40}}>
                            <Text style={{fontSize:24,fontWeight:'bold',color:'#FFFFFF'}}>
                                {locale?._('Pool.title')}
                            </Text>
                            {
                                bShowTip?
                                    <View style={{flexDirection:"row",marginTop:20,alignItems:"center"}}>
                                        <ActivityIndicator
                                        animating = {true}
                                        color={'#0155bc'}
                                        size={'small'}
                                        />
                                        <Text style={{marginLeft:10,fontSize:10,color:'#BCB6F2'}}>{showNeedExcuteContent()}</Text>
                                    </View>
                                    :null
                            }
                        </View>
                    </ImageBackground>
                    {/***创建质押合约  合约搜索****/}
                    <View style={{height:180,backgroundColor:'#fff',marginTop:-30
                        ,borderLeftWidth:1,borderTopLeftRadius:20,borderLeftColor:'#ffffff'
                        ,borderRightWidth:1,borderTopRightRadius:20,borderRightColor:'#ffffff'
                        ,alignItems:'center'
                    }}>
                        <TouchableOpacity style={{width:334,height:48,backgroundColor:'#7367E3',justifyContent:'center'
                            ,alignItems:'center',borderWidth:1,borderColor:'#7367E3',borderRadius:10,alignSelf:'center'
                            ,marginTop:30,marginBottom:20
                        }} onPress={()=>{
                            if(bShowTip){
                                Alert.alert(locale?._('Pool.op.excuting')+'', showNeedExcuteContent(),[{text:'确定',onPress:()=>{
                                }}]);
                            }else{
                                setTransferCreateVisible(true);
                            }
                            }}>
                            <Text style={{fontSize:16,color:'#ffffff',textAlign:'center'}}>
                                {locale?._('Pool.zyhy.create')}
                            </Text>
                        </TouchableOpacity>

                        <TouchableOpacity style={{
                                 width:334
                                ,height:48
                                ,flexDirection:'row'
                            }}
                            onPress={()=>
                                {
                                    console.log("onPress =====>>"+fetchCopiedText);
                                    fetchCopiedText()
                                }}
                            >
                        <View
                              style={{
                                  width:'100%'
                                  ,height:48
                                  ,backgroundColor:'#E7E7E8'
                                  ,marginTop:10
                                  ,borderWidth:1
                                  ,borderRadius:10
                                  ,borderColor:'#E7E7E8'
                                  ,flexDirection:'row'
                         }}
                         >
                            <ImageBackground
                             source={pool_find}
                             style={{ width: 15, height:15, margin:25,marginRight:0
                                ,alignSelf:'center',alignItems:'center'}} />
                            <TextInput
                                underlineColorAndroid={'transparent'}
                                placeholder= {locale?._('Pool.zyhy.qryHint')}
                                defaultValue={seachTxt}
                                // selectTextOnFocus={true}
                                // pointerEvents={'auto'}
                                // enablesReturnKeyAutomatically={false}
                                // onselectstart="return false;" onpaste="return false;" type="text"
                                onChangeText={
                                    (value) => setSeachTxt(value.trim())
                                }
                                onEndEditing={inputOnEndEditing}
                                style={{
                                    width:260,
                                    marginLeft:24
                                }
                            }
                            />
                        </View>
                        </TouchableOpacity>
                    </View>

                        {/* 我的质押    */}
                        {
                        bhyMyListShow === true?
                            <View style={{backgroundColor:"#fff"}}>
                                <View style={{flexDirection:'row'}}>
                                    <Text style={{fontSize:15,color:'#14141A',margin:15}}>
                                        {locale?._('Pool.zyhy_my')}
                                    </Text>
                                    <Text style={{fontSize:12,color:'#14141A',margin:15,position:'absolute',right:0,bottom:0}}>
                                        {locale?._('Pool.zyhy_rec').replace('zhy',hyMyList.length)}
                                    </Text>
                                </View>
                                <View>
                                    {/**{"Address":"gcLcf7oAWbAJFMFSo15w9vuvDdpkNjrAU","Contract":null,"Amount":"40421990.6569","Start":1,"End":-1,"LBH":275037}**/}
                                    {
                                        hyMyList.map((item:any,index:any)=>(

                                            <TouchableOpacity
                                                key={index}
                                            style={{margin:15,borderColor:'#8a8a8a',borderWidth:1,borderRadius:10}}
                                            onPress={()=>
                                                {
                                                    navigation.navigate('PoolOp',
                                                    {
                                                        //是否能进行操作的数据
                                                        addressIn,
                                                        operateType,
                                                        requestMoney,
                                                        bShowTip,
                                                        //合约数据
                                                        item,
                                                        // itemContractState:contractAddressEqual(item,index),
                                                        itemContractState:log(parseInt(status[index]) ),
                                                        //钱包地址;
                                                        walletAddress:wallet.address
                                                        //合约地址;
                                                        ,itemContract:JSON.stringify(item).split(',')[0].replace('[','').replace('\\"','').replace('\\"','').replace('\"','')
                                                        //年化率
                                                        ,rateYear:parseFloat(calculateYearRate(item))>1000?1000:calculateYearRate(item)
                                                        ,updateData: function (isNeedWait:boolean, addressIn:string, operateType:string, requestMoney:any) {
                                                            console.log("PoolOp Go Back refresh ====>>>>"+isNeedWait+' '+addressIn+' '+operateType+' '+requestMoney+' ');
                                                            getPreviousParams(isNeedWait,addressIn,operateType,requestMoney);
                                                          }
                                                        ,}
                                                    )
                                                }
                                                }>

                                        <View style={{flexDirection:'row',justifyContent:'space-around',paddingLeft:20}}>
                                        <View style={{flex:2,marginLeft:0}}>
                                            {/***资金池***/}
                                            <Text style={{fontSize:fontSizeZy,color:colorZy,marginTop:8}}>{locale?._('Pool.zyhy_zjc')}</Text>
                                            <Text style={{fontSize:fontSizeValue,color:'#14141A',fontWeight:'bold',marginTop:8,width:0.5*width,marginBottom:buttomInterval}}>
                                            {formartMoney(JSON.stringify(item).split(',')[JSON.stringify(item).split(',').length-5].replace('[','').replace('\\"','').replace('\\"','').replace('\"',''),4)}
                                            </Text>
                                            {/***总额度***/}
                                            <Text style={{fontSize:fontSizeZy,color:colorZy,marginTop:8}}>{locale?._('Pool.zyhy_zed')}</Text>
                                            <Text style={{fontSize:fontSizeValue,color:'#14141A',fontWeight:'bold',marginTop:8,width:0.5*width,marginBottom:buttomInterval}}>

                                                {formartMoney(JSON.stringify(item).split(',')[JSON.stringify(item).split(',').length-2].replace('[','').replace('\\"','').replace('\\"','').replace('\"',''),4)}

                                                </Text>
                                            {/***我的凭证***/}
                                            <Text style={{fontSize:fontSizeZy,color:colorZy,marginTop:8}}>{locale?._('Pool.zyhy_mypz')}</Text>
                                            <Text style={{fontSize:fontSizeValue,color:'#14141A',fontWeight:'bold',marginTop:8,width:0.5*width}}>
                                                {formartMoney(JSON.stringify(item).split(',')[JSON.stringify(item).split(',').length-3].replace('[','').replace('\\"','').replace('\\"','').replace('\"',''),4)}
                                                </Text>
                                        </View>
                                        <View style={{flex:2,marginLeft:55}}>
                                            <View style={{flexDirection:'row'}}>
                                                <View>
                                                    {/***年化率***/}
                                                    <Text style={{fontSize:fontSizeZy,color:colorZy,marginTop:8}}>{locale?._('Pool.zyhy_nhl')}</Text>
                                                    <Text style={{fontSize:fontSizeValue,color:'#F92360',fontWeight:'bold',marginTop:8,marginBottom:buttomInterval}}>
                                                        {/* 我的资金：占比*资金池 */}
                                                        {/* 年化率：(4204800*占比/我的资金) */}

                                                        {parseFloat(calculateYearRate(item))>1000?1000+"%":calculateYearRate(item)+"%"}
                                                        {/* {parseFloat(JSON.stringify(item).split(',')[JSON.stringify(item).split(',').length-5].replace('[','').replace('\\"','').replace('\\"','').replace('\"',''))} */}

                                                        </Text>
                                                </View>
                                                {/*<View>*/}
                                                {/*    /!***状态***!/*/}
                                                {/*    <Text style={{fontSize:12,color:'#D9DCE6',marginTop:8}}>{locale?._('Pool.zyhy_zt')}</Text>*/}
                                                {/*    <View style={{flexDirection:'row'}}>*/}
                                                {/*        <View style={{backgroundColor:'#f9f992',width:2,height:8}}/>*/}
                                                {/*    </View>*/}
                                                {/*</View>*/}
                                            </View>
                                            {/***我的占比***/}
                                            <Text style={{fontSize:fontSizeZy,color:colorZy,marginTop:8}}>{locale?._('Pool.zyhy_myzb')}</Text>
                                            <Text style={{fontSize:fontSizeValue,color:'#14141A',fontWeight:'bold',marginTop:8,marginBottom:buttomInterval,width:0.5*width}}>
                                                {/* 占比 = 我的凭证/总凭证 */}
                                                {
                                                    formartMoney((calculateMyPercent(item)*100).toString(),4)+"%"
                                                }
                                                </Text>
                                            {/***我的余额***/}
                                            <Text style={{fontSize:fontSizeZy,color:colorZy,marginTop:8}}>{locale?._('Pool.zyhy_mysy')}</Text>
                                            <Text style={{fontSize:fontSizeValue,color:'#7367E3',fontWeight:'bold',marginTop:8,width:0.5*width}}>
                                                {/* 1000.993557333 */}
                                                {
                                                formartMoney(calculateMyIncome(item).toString(),4)
                                                }
                                                </Text>
                                        </View>
                                        {/* 我的状态; */}
                                        {
                                        !contractAddressEqual(item,index)?
                                            <View style={{flex:1}}>
                                                <Text style={{fontSize:12,color:colorZy,marginTop:8}}>{locale?._('Pool.zyhy_zt')}</Text>
                                                <View style={{flexDirection:'row',marginTop:10}}>
                                                    <View style={PoolStyle.statusOffline}/>
                                                    <View style={PoolStyle.statusOffline}/>
                                                    <View style={PoolStyle.statusOffline}/>
                                                    <View style={PoolStyle.statusOffline}/>
                                                    <View style={PoolStyle.statusOffline}/>
                                                    <View style={PoolStyle.statusOffline}/>
                                                </View>
                                            </View>
                                            :
                                            <View style={{flex:1}}>
                                                <Text style={{fontSize:fontSizeZy,color:colorZy,marginTop:8}}>{locale?._('Pool.zyhy_zt')}</Text>
                                                <View style={{flexDirection:'row',marginTop:10}}>
                                                    {
                                                        ( log(parseInt(status[index])|| 20)>0)?<View style={PoolStyle.statusOnline}/>:   <View style={PoolStyle.statusOffline}/>
                                                    }
                                                    {
                                                        ( log(parseInt(status[index])|| 20) >=4)?<View style={PoolStyle.statusOnline}/>:   <View style={PoolStyle.statusOffline}/>
                                                    }
                                                    {
                                                        ( log(parseInt(status[index])|| 20) >=8)?<View style={PoolStyle.statusOnline}/>:   <View style={PoolStyle.statusOffline}/>
                                                    }
                                                    {
                                                        ( log(parseInt(status[index])|| 20) >=12)?<View style={PoolStyle.statusOnline}/>:   <View style={PoolStyle.statusOffline}/>
                                                    }
                                                    {
                                                        ( log(parseInt(status[index])|| 20) >=16)?<View style={PoolStyle.statusOnline}/>:   <View style={PoolStyle.statusOffline}/>
                                                    }
                                                    {
                                                        ( log(parseInt(status[index])|| 20) >=20)?<View style={PoolStyle.statusOnline}/>:   <View style={PoolStyle.statusOffline}/>
                                                    }
                                                    {/*<View style={PoolStyle.statusOnline}/>*/}
                                                    {/*<View style={PoolStyle.statusOnline}/>*/}
                                                    {/*<View style={PoolStyle.statusOnline}/>*/}
                                                    {/*<View style={PoolStyle.statusOnline}/>*/}
                                                    {/*<View style={PoolStyle.statusOnline}/>*/}
                                                    {/*<View style={PoolStyle.statusOnline}/>*/}
                                                </View>
                                            </View>

                                        }
                                    </View>
                                     {/***打印图标+质押ID****/}
                                    <View style={{height:1,backgroundColor:'#F3F2F3',marginTop:8,marginBottom:10,marginLeft:20,marginRight:20}}/>
                                    <View style={{flexDirection:'row',marginBottom:10}}>
                                        <ImageBackground source={pool_print} style={{ width: 15, height:15, marginLeft:20,alignSelf:'center',alignItems:'center'}} />
                                        <Text style={{fontSize:12,color:colorZy,marginLeft:5,fontWeight:"bold"}}>
                                        {JSON.stringify(item).split(',')[0].replace('[','').replace('\\"','').replace('\\"','').replace('\"','')}
                                        </Text>
                                    </View>
                                            </TouchableOpacity>
                                        ))
                                    }
                                </View>
                            </View>
                            :null
                    }

                    {/***“质押合约列表”    当前11条****/}
                    {
                        bhyAllListShow?
                            <View >
                                <View style={{flexDirection:'row'}}>
                                    <TouchableOpacity onLongPress={workAllList2} activeOpacity={1}>
                                        <Text style={{fontSize:15,color:'#14141A',margin:15}}>
                                            {locale?._('Pool.zyhy_all')}
                                        </Text>
                                    </TouchableOpacity>
                                    <Text style={{fontSize:12,color:'#14141A',margin:15,position:'absolute',right:0,bottom:0}}>
                                        {locale?._('Pool.zyhy_rec').replace('zhy',hyAllList.length)}
                                    </Text>
                                </View>
                                <View>
                                    {/**{"Address":"gcLcf7oAWbAJFMFSo15w9vuvDdpkNjrAU","Contract":null,"Amount":"40421990.6569","Start":1,"End":-1,"LBH":275037}**/}
                                    {
                                        hyAllList.map(( item:any,index:any
                                                            )=>(
                                            <TouchableOpacity
                                                key={index}
                                            style={{margin:15,borderColor:'#8a8a8a',borderWidth:1,borderRadius:10}}
                                            onPress={()=>
                                                // navigation.navigate('PoolOp',
                                                // //总额度
                                                // {amountMoney:item.Amount
                                                //     //年化率
                                                //     ,rateYear:Math.ceil(4204800/parseFloat(item.Amount+'') *100)
                                                //     //状态;
                                                //     ,status:'true'
                                                //     //我的凭证;
                                                //     ,myProof:info[5]?info[5]:0
                                                //     //质押ID;
                                                //     ,mortgageID:item.Contract
                                                //     ,}
                                                // )
                                                {
                                                    // if(bShowTip){
                                                    //     //locale?._('Pool.op.excuting')
                                                    //     Alert.alert('', showNeedExcuteContent(),[{text:'确定',onPress:()=>{
                                                    //     }}]);
                                                    //     return;
                                                    // }
                                                    navigation.navigate('PoolOp',
                                                    {
                                                        //是否能进行造作的数据
                                                        addressIn,
                                                        operateType,
                                                        requestMoney,
                                                        bShowTip,
                                                        //合约数据
                                                        item:"",
                                                        // itemContractState:searchResultIsOnLine(item),
                                                        itemContractState:parseInt(item.status || "20"),
                                                        //钱包地址;
                                                        walletAddress:wallet.address
                                                        //合约地址;
                                                        ,itemContract:item.Contract
                                                        //年化率
                                                        ,rateYear:Math.ceil(4204800/parseFloat(item.Amount+'') *100)>1000?1000:Math.ceil(4204800/parseFloat(item.Amount+'') *100)
                                                        ,updateData: function (isNeedWait:boolean, addressIn:string, operateType:string, requestMoney:any) {
                                                            console.log("PoolOp Go Back refresh ====>>>>"+isNeedWait+' '+addressIn+' '+operateType+' '+requestMoney+' ');
                                                            getPreviousParams(isNeedWait,addressIn,operateType,requestMoney);
                                                          }
                                                        ,}
                                                    )
                                                }
                                                }>
                                                <View style={{flexDirection:'row'}}>
                                                    <View style={{flex:1,marginLeft:15,marginRight:8}}>
                                                        {/***资金池***/}
                                                        <Text style={{fontSize:fontSizeZy,color:colorZy,marginTop:8}}>{locale?._('Pool.zyhy_zjc')}</Text>
                                                        <Text style={{fontSize:fontSizeValue,color:'#14141A',fontWeight:'bold',marginTop:8}}>{item.Amount}</Text>
                                                    </View>
                                                    <View style={{flex:1,marginRight:0}}>
                                                        <View style={{flexDirection:'row'}}>
                                                            <View style={{marginRight:50}}>
                                                                {/***年化率***/}
                                                                <Text style={{fontSize:fontSizeZy,color:colorZy,marginTop:8}}>{locale?._('Pool.zyhy_nhl')}</Text>
                                                                <Text style={{fontSize:fontSizeValue,color:'#F92360',fontWeight:'bold',marginTop:8}}>
                                                                {
                                                                // parseInt(4204800/item.Amount *100)
                                                                // 4204800/parseFloat('22') *100
                                                                Math.ceil(4204800/parseFloat(item.Amount+'') *100)>1000?1000:Math.ceil(4204800/parseFloat(item.Amount+'') *100)
                                                                }%
                                                                </Text>
                                                            </View >
                                                            <View style={{alignItems:"flex-start"}}>
                                                                {/***状态***/}
                                                                <Text style={{fontSize:fontSizeZy,color:colorZy,marginTop:8}}>{locale?._('Pool.zyhy_zt')}</Text>
                                                                <View style={{flexDirection:'row',marginTop:10}}>
                                                                {
                                                                    parseInt(item.status || "20")>=0?<View style={PoolStyle.statusOnline}/>:   <View style={PoolStyle.statusOffline}/>
                                                                }
                                                                {
                                                                    parseInt(item.status || "20")>=4?<View style={PoolStyle.statusOnline}/>:   <View style={PoolStyle.statusOffline}/>
                                                                }
                                                                {
                                                                    parseInt(item.status || "20")>=8?<View style={PoolStyle.statusOnline}/>:   <View style={PoolStyle.statusOffline}/>
                                                                }
                                                                {
                                                                    parseInt(item.status || "20")>=12?<View style={PoolStyle.statusOnline}/>:   <View style={PoolStyle.statusOffline}/>
                                                                }
                                                                {
                                                                    parseInt(item.status || "20")>=16?<View style={PoolStyle.statusOnline}/>:   <View style={PoolStyle.statusOffline}/>
                                                                }
                                                                {
                                                                    parseInt(item.status || "20")>=20?<View style={PoolStyle.statusOnline}/>:   <View style={PoolStyle.statusOffline}/>
                                                                }
                                                                </View>
                                                            </View>
                                                        </View>
                                                    </View>
                                                </View>
                                                <View style={{height:1,backgroundColor:'#F3F2F3',marginTop:8,marginBottom:10,marginLeft:20,marginRight:20}}/>
                                                <View style={{flexDirection:'row',alignItems:'center',marginBottom:10}}>
                                                    {/***打印图标+质押ID****/}
                                                    <ImageBackground source={pool_print} style={{ width: 15, height:15, marginLeft:20,alignSelf:'center',alignItems:'center'}} />
                                                    <Text style={{fontSize:12,color:colorZy,marginLeft:5,fontWeight:"bold"}}>
                                                        {item.Contract}
                                                        </Text>
                                                </View>
                                            </TouchableOpacity>
                                        ))
                                    }
                                </View>
                            </View>
                            :null
                    }
                    {/*******/}
                    {/*******/}
                    {/***创建质押合约对话框***/}
                    <BottomSheet isVisible={transferCreateVisible} modalProps = {{
                        statusBarTranslucent: true,
                        // visible: recentVisible
                    }}>

                        <View style={{
                            backgroundColor: 'white',
                            borderTopLeftRadius: 27,
                            borderTopRightRadius: 27,
                            minHeight: 520,
                            alignItems:"center",
                        }}>
                            {/****创建质押合约****/}

                            {/***有一个横杠图标***/}
                            <TouchableOpacity style={{backgroundColor:'#E7E7E8',width:120,height:10,borderColor:'#E7E7E8',borderRadius:20,borderWidth:1,
                                alignSelf:'center',marginTop:20,marginBottom:10
                            }}  onPress={() => setTransferCreateVisible(false)}
                            />

                            {/****7335221.33982356*****/}
                            <Text style={{fontSize:40,fontWeight:'bold',color:'#7468E3',textAlign:'center',marginTop:30}}>{formartMoney(balances.SAT, 4)}</Text>

                            {/****可用奖金池*****/}
                            <Text style={{fontSize:18,fontWeight:'bold',color:'#14141A',textAlign:'center',marginTop:10}}>{locale?._('Pool.zyhy.createHint')}</Text>
                            {/***输入合约金额 后面有一个SAT图标**/}
                            <View style={{width:334,height:48,backgroundColor:'#E7E7E8',marginTop:10, marginLeft:15
                                , borderWidth:1,borderRadius:10,borderColor:'#E7E7E8', flexDirection:'row'
                            }}>
                                <TextInput
                                    underlineColorAndroid={'transparent'}
                                    placeholder={locale?._('Pool.zyhy.create_moneyHint')}
                                    value={hyMoney}
                                    onChangeText={(value) => {
                                        // @ts-ignore
                                        value = value.match(/^\d*(\.?\d{0,8})/g)[0];
                                        setHyMoney(value)
                                        }
                                    }
                                    style={{width:260,marginLeft:24}}
                                />
                                <Text style={{fontSize:16,color:'#9A9AA7',alignSelf:'center'}}>SAT</Text>
                            </View>
                            {/***创建*****/}
                            <View style={{ flexDirection: 'row',position:'absolute',alignSelf:"center",bottom:80,alignItems:"center" }}>
                                <TouchableOpacity style={{ width:334,height:40,justifyContent: 'center',backgroundColor:'#7367E3',alignItems:'center'
                                    ,borderColor:'#7367E3',borderWidth:1,borderRadius:10 }} onPress={()=>
                                    {
                                        parseInt(hyMoney)<100000?
                                            Alert.alert("",locale?._("pool.op.minCreateContract"),[{text: (locale?._('Assets.send.OK') as any)}])
                                            :
                                        onCreateHy(hyMoney);
                                    }}>
                                    <Text style={{
                                        // marginTop: 160,
                                        fontSize: 20,
                                        textAlign: 'center',
                                        color: 'white'
                                    }}>{locale?._('Pool.btn_create')}</Text>
                                </TouchableOpacity>
                            </View>
                            <View  style={{ flexDirection:'row', position:'absolute', bottom:30, alignItems:"center"}} >
                                <TouchableOpacity style={{ width:334, height:40, justifyContent: 'center', backgroundColor:'#7367E3', alignItems:'center'
                                  , borderColor:'#7367E3', borderWidth:1, borderRadius:10 }} onPress={
                                      ()=>{
                                         setTransferCreateVisible(false)
                                      }
                                  }>
                                <Text style={{fontSize:20,textAlign:'center',color:'white'}}>{locale?._('cancel')}</Text>
                                </TouchableOpacity>
                            </View>
                        </View>
                    </BottomSheet>
                    {/* @ts-ignore*/}
                    <WaitingModal show={bshow} prompt={prompt}/>{/***2021-03-06*/}
                    {/* @ts-ignore*/}
                    <LoadingView showLoading={ bShowLoading } />{/***2021-03-06*/}


                </View>

            </ScrollView>
            <RedEnvelopeLoad visible={showRedEnvelopeLoad} back={RedEnvelopeLoadBack} sender={sender} loadType={loadType} bless={coverTxt}/>
        </View>
    );
};

const PoolStyle = StyleSheet.create({
    statusOnline:{
        backgroundColor:'#1B9749'
        ,width:4
        ,height:16
        ,marginRight:2
        ,borderWidth:1
        ,borderRadius:2
        ,borderColor:'#1B9749'
    },
    statusOffline:{
        backgroundColor:'#ffffff'
        ,width:4
        ,height:16
        ,marginRight:2
        ,borderWidth:1
        ,borderRadius:2
        ,borderColor:'#1B9749'
    }
});

export default Pool;
